package com.aiyige.page.launch;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.db.table.AdModel;
import com.aiyige.city.util.CityUtil;
import com.aiyige.page.advertisement.util.AdUtil;
import com.aiyige.page.login.model.impl.LoginManager;
import com.aiyige.utils.AppErrorDialog;
import com.aiyige.utils.AppUtils;
import com.aiyige.utils.PermissionUtil;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.widget.RequestPermissionDialog;
import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;

import java.util.List;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;
import timber.log.Timber;

@RuntimePermissions
@Route(path = ARouterConfig.LaunchPage)
public class LaunchPage extends BaseActivity implements DialogInterface.OnCancelListener {
    public static final int REQUEST_CODE_GO_TO_APP_SETTING = 123;
    private CountDownTimer countDownTimer;
    InitTask initTask;
    View initLayout;
    AdModel adModel = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_launch);
        initLayout = findViewById(R.id.initLayout);
        LaunchPagePermissionsDispatcher.checkPermissionWithPermissionCheck(this);
    }


    @Override
    public void onBackPressed() {
    }

    public void startCountDown() {
        //最多等待1秒
        countDownTimer = new CountDownTimer(100, 100) {
            @Override
            public void onTick(long millisUntilFinished) {
            }

            @Override
            public void onFinish() {
//                Postcard postcard = ARouter.getInstance()
//                        .build(ARouterConfig.MainPage)
//                        .withTransition(R.anim.activity_still_short, 0);
//                if (adModel != null) {
//                    postcard.withParcelable("adModel", adModel);
//                }
//                postcard.navigation(LaunchPage.this);

                ARouter.getInstance().build(ARouterConfig.TestQNPlayerPage).navigation();
            }
        };
        countDownTimer.start();
    }

    public void initApp() {
        initTask = new InitTask();
        initTask.execute();
    }

    @NeedsPermission({
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.CHANGE_WIFI_STATE,
            Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
            Manifest.permission.READ_PHONE_STATE
    })
    void checkPermission() {
        initApp();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        LaunchPagePermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale({
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.CHANGE_WIFI_STATE,
            Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
            Manifest.permission.READ_PHONE_STATE
    })
    void onShowRationale(final PermissionRequest request) {
        List<String> ungrantedPermissionList = PermissionUtil.pickUngrantedPremission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.CHANGE_WIFI_STATE,
                Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
                Manifest.permission.READ_PHONE_STATE
        );
        List<String> ungrantedPermissionTitleList = PermissionUtil.batchConvertPermissionToReadableString(this, ungrantedPermissionList);
        RequestPermissionDialog requestPermissionDialog = RequestPermissionDialog.newInstance(StringUtils.getString(R.string.app_need_permission), TextUtils.join("\n", ungrantedPermissionTitleList));
        requestPermissionDialog.setListner(new RequestPermissionDialog.Listener() {
            @Override
            public void onClickOk() {
                request.proceed();
            }

            @Override
            public void onCancel() {
                finish();
            }
        });
        requestPermissionDialog.show(getSupportFragmentManager(), "");


    }

    @OnPermissionDenied({
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.CHANGE_WIFI_STATE,
            Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
            Manifest.permission.READ_PHONE_STATE
    })
    void onPermissionDenied() {
        List<String> ungrantedPermissionList = PermissionUtil.pickUngrantedPremission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.CHANGE_WIFI_STATE,
                Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
                Manifest.permission.READ_PHONE_STATE
        );
        List<String> ungrantedPermissionTitleList = PermissionUtil.batchConvertPermissionToReadableString(this, ungrantedPermissionList);
        RequestPermissionDialog requestPermissionDialog = RequestPermissionDialog.newInstance(StringUtils.getString(R.string.app_really_need_permission), StringUtils.getString(R.string.please_grant_permission), StringUtils.getString(R.string.ok2));
        requestPermissionDialog.setListner(new RequestPermissionDialog.Listener() {
            @Override
            public void onClickOk() {
                LaunchPagePermissionsDispatcher.checkPermissionWithPermissionCheck(LaunchPage.this);
            }

            @Override
            public void onCancel() {
                finish();
            }
        });
        requestPermissionDialog.show(getSupportFragmentManager(), "");
    }

    @OnNeverAskAgain({
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.CHANGE_WIFI_STATE,
            Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
            Manifest.permission.READ_PHONE_STATE
    })
    void onNeverAskAgain() {
        List<String> ungrantedPermissionList = PermissionUtil.pickUngrantedPremission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.CHANGE_WIFI_STATE,
                Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
                Manifest.permission.READ_PHONE_STATE
        );
        List<String> ungrantedPermissionTitleList = PermissionUtil.batchConvertPermissionToReadableString(this, ungrantedPermissionList);
        RequestPermissionDialog requestPermissionDialog = RequestPermissionDialog.newInstance(StringUtils.getString(R.string.grant_permission_in_setting), TextUtils.join("\n", ungrantedPermissionTitleList));
        requestPermissionDialog.setListner(new RequestPermissionDialog.Listener() {
            @Override
            public void onClickOk() {
                AppUtils.gotoAppSetting(LaunchPage.this, REQUEST_CODE_GO_TO_APP_SETTING);
            }

            @Override
            public void onCancel() {
                finish();
            }
        });
        requestPermissionDialog.show(getSupportFragmentManager(), "");
    }

    @Override
    public void onCancel(DialogInterface dialog) {
        finish();
    }

    public class InitTask extends AsyncTask<Object, Object, Object> {


        @Override
        protected void onPreExecute() {
            CityUtil.installUpdateAlarm();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            long timestamp = System.currentTimeMillis();
            adModel = AdUtil.getShouldPlayAd();
            try {
                CityUtil.copyCityFromAsset();
                CityUtil.populateCityList();
                LoginManager.getInstance().onStartAppDoSomething();
                Timber.e("init use time:" + (System.currentTimeMillis() - timestamp));
                return null;
            } catch (Exception e) {
                return e;
            }

        }

        @Override
        protected void onPostExecute(Object o) {
            initLayout.setVisibility(View.INVISIBLE);
            CityUtil.updateCityIfTooOld();
            AdUtil.maybeUpdateAd();
            if (o instanceof Exception) {
                AppErrorDialog.newInstance(StringUtils.getString(R.string.app_init_failed), new AppErrorDialog.Callback() {
                    @Override
                    public void onConfirm() {
                        finish();
                        System.exit(0);
                    }
                }).show(getSupportFragmentManager(), "");
            } else {
                startCountDown();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_GO_TO_APP_SETTING:
                LaunchPagePermissionsDispatcher.checkPermissionWithPermissionCheck(this);
                break;
            default:
                super.onActivityResult(requestCode, resultCode, data);
                break;
        }
    }


}
